using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using ZuDoKu.Utilities;

namespace ZuDoKu
{
    public class ControlCollection : CollectionBase, IEnumerable<Control>
    {
        private Screen _screen;
        public Screen Screen
        {
            get { return _screen; }
            internal set 
            { 
                _screen = value;
                foreach (Control c in this)
                {
                    c.Screen = _screen;
                }
            }
        }

        internal ControlCollection(Screen screen)
        {
            _screen = screen;
        }

        public void Add(Control control)
        {
            InnerList.Add(control);
            control.Screen = _screen;
            OnAdded(control);
        }


        internal void AddRange(IEnumerable<Control> controls)
        {
            foreach (Control c in controls)
            {
                Add(c);
            }
        }

        public Control this[int index]
        {
            get { return (Control)InnerList[index]; }
            set 
            { 
                InnerList[index] = value;
                value.Screen = _screen;
            }
        }

        public void Remove(Control control)
        {
            InnerList.Remove(control);
            control.Screen = null;
        }

        public event EventHandler<EventArgs<Control>> Added;
        protected void OnAdded(Control control)
        {
            if (Added != null) Added(this, new EventArgs<Control>(control));
        }

        public event EventHandler<EventArgs<Control>> Removed;
        protected void OnRemoved(Control control)
        {
            if (Removed != null) Removed(this, new EventArgs<Control>(control));
        }

        public Control[] ToArray()
        {
            Control[] controls = new Control[InnerList.Count];
            Array.Copy(InnerList.ToArray(), controls, InnerList.Count);

            return controls;
        }

        #region IEnumerable<Control> Members

        public new IEnumerator<Control> GetEnumerator()
        {
            foreach (Control c in this.InnerList)
                yield return c;
        }

        #endregion
    }

    internal class ControlDrawOrderSorter : IComparer
    {
        #region IComparer Members

        public int Compare(object x, object y)
        {
            Control a = x as Control;
            Control b = y as Control;

            if (a == null)
                throw new ArgumentException("Object must be a Control", "x");
            if (b == null)
                throw new ArgumentException("Object must be a Control", "y");

            return a.DrawOrder.CompareTo(b.DrawOrder);
        }

        #endregion
    }
}
